package org.ece3574.WTParty;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class FBTestActivity extends Activity implements OnClickListener, LoginListener{
	
	private Button btnLogin;
	private ListView lvFriends;
	private WTParty wtParty;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.friends);
    	lvFriends = (ListView)findViewById(R.id.lvFriends);
        btnLogin = (Button)findViewById(R.id.btnLogin);
        btnLogin.setOnClickListener(this);
        wtParty = WTParty.getInstance(this);
        
    	if(wtParty.isLoggedIn())
    	{
    		loginSuccessful();
    	}

    }
    
    public void loginSuccessful()
    {
    	displayFriends();
    	btnLogin.setVisibility(View.GONE);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        wtParty.handleFacebookCallback(requestCode, resultCode, data);
        Log.d(getLocalClassName(), "Facebook callback");
    }
    
    private class FriendListUpdater extends AsyncTask<Void, Void, String[]>
    {

		@Override
		protected String[] doInBackground(Void... arg0) {
			String[] friendList = wtParty.getFriends();
    		return friendList;
		}
		
		protected void onPostExecute(String[] friendList)
		{
			setFriendsList(friendList);
		}
    	
    }
    
    private void setFriendsList(String[] friendList)
    {
		if(friendList!=null)
		{
			ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.list_item_elem, friendList);
			lvFriends.setAdapter(aa);
		}
    }

	
	private void displayFriends()
	{
		new FriendListUpdater().execute((Void)null);
	}

	public void onClick(View v) {
		if(v == btnLogin)
		{
			wtParty.login(this, this);
		}
	}
}